package com.zp.business.impl.infusion;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zp.base.api.vo.PerformFreqDictVo;
import com.zp.business.api.diagnosis.HisDiagnosis;
import com.zp.business.api.diagnosis.HisDiagnosisVo;
import com.zp.business.api.prescription.PrescriptionItem;
import com.zp.business.entity.infusion.InfusionItem;
import com.zp.business.entity.infusion.InfusionRegister;
import com.zp.business.entity.infusion.InfusionRegisterStay;
import com.zp.business.entity.infusion.bo.InfusionRegisterBo;
import com.zp.business.entity.infusion.vo.InfusionPrescriptionVo;
import com.zp.business.entity.infusion.vo.InfusionRegisterVo;
import com.zp.business.entity.patient.vo.ClinicMasterVo;
import com.zp.business.mapper.diagnosis.HisDiagnosisMapper;
import com.zp.business.mapper.infusion.InfusionItemMapper;
import com.zp.business.mapper.infusion.InfusionRegisterMapper;
import com.zp.business.mapper.infusion.InfusionRegisterStayMapper;
import com.zp.business.mapper.prescription.PrescriptionItemMapper;
import com.zp.business.service.infusion.IInfusionRegisterService;
import com.zp.common.core.constant.CacheNames;
import com.zp.common.core.constant.UserConstants;
import com.zp.common.core.utils.DateUtils;
import com.zp.common.core.utils.SnowIdUtils;
import com.zp.common.core.utils.StringUtils;
import com.zp.common.myBatis.core.page.PageQuery;
import com.zp.common.myBatis.core.page.TableDataInfo;
import com.zp.common.redis.utils.CacheUtils;
import com.zp.system.api.entity.SysDept;
import com.zp.system.api.entity.SysOrg;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 输液室登记主Service业务层处理
 *
 * @author zhang peng
 * @ date 2025-02-08
 */
@RequiredArgsConstructor
@Service
public class InfusionRegisterServiceImpl implements IInfusionRegisterService {

    static Map<String, SysDept> sysDeptMap = CacheUtils.get(CacheNames.SYS_DEPT);
    static Map<String, SysOrg> sysOrgMap = CacheUtils.get(CacheNames.SYS_ORG);
    static Map<String, PerformFreqDictVo> performFreqDictMap = CacheUtils.get(CacheNames.PERFORM_FREQ_DICT);
    private final InfusionRegisterMapper baseMapper;
    private final InfusionItemMapper infusionItemMapper;
    private final InfusionRegisterStayMapper infusionRegisterStayMapper;
    private final PrescriptionItemMapper prescriptionItemMapper;
    private final HisDiagnosisMapper hisDiagnosisMapper;

    /**
     * 查询输液室登记主
     */
    @Override
    public InfusionRegisterVo queryById(String infusionRegisterId) {
        return baseMapper.selectVoById(infusionRegisterId);
    }

    /**
     * 查询输液室登记主列表(分页)
     */
    @Override
    public TableDataInfo<InfusionRegisterVo> queryPageList(InfusionRegisterBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<InfusionRegister> lqw = buildQueryWrapper(bo);
        Page<InfusionRegisterVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询输液室登记主列表(不分页)
     */
    @Override
    public List<InfusionRegisterVo> queryList(InfusionRegisterBo bo) {
        LambdaQueryWrapper<InfusionRegister> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<InfusionRegister> buildQueryWrapper(InfusionRegisterBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<InfusionRegister> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getClinicId()), InfusionRegister::getClinicId, bo.getClinicId());
        lqw.eq(StringUtils.isNotBlank(bo.getInfusionNo()), InfusionRegister::getInfusionNo, bo.getInfusionNo());
        lqw.eq(StringUtils.isNotBlank(bo.getRegisterDept()), InfusionRegister::getRegisterDept, bo.getRegisterDept());
        lqw.eq(StringUtils.isNotBlank(bo.getOrgId()), InfusionRegister::getOrgId, bo.getOrgId());
        lqw.eq(StringUtils.isNotBlank(bo.getRemarks()), InfusionRegister::getRemarks, bo.getRemarks());
        lqw.like(StringUtils.isNotBlank(bo.getRegisterDeptName()), InfusionRegister::getRegisterDeptName, bo.getRegisterDeptName());
        lqw.like(StringUtils.isNotBlank(bo.getOrgName()), InfusionRegister::getOrgName, bo.getOrgName());
        return lqw;
    }

    /**
     * 新增输液室登记主
     */
    @Override
    @Transactional
    public Boolean insertByBo(InfusionRegisterBo bo) {
        InfusionRegister add = new InfusionRegister();
        add.setInfusionRegisterId(SnowIdUtils.uniqueString());
        add.setClinicId(bo.getClinicId());
        add.setOrgId(bo.getOrgId());
        add.setRegisterDeptName(StringUtils.isNotBlank(add.getRegisterDept()) && CollectionUtil.isNotEmpty(sysDeptMap)
                && ObjectUtil.isNotNull(sysDeptMap.get(add.getRegisterDept())) ? sysDeptMap.get(add.getRegisterDept()).getDeptName() : "");
        String orgName = !sysOrgMap.isEmpty() && StringUtils.isNotBlank(bo.getOrgId())
                ? sysOrgMap.get(bo.getOrgId()).getOrgName() : "";
        add.setOrgName(orgName);
        add.initEntity();
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            List<InfusionItem> infusionItemList = new ArrayList<>();
            List<InfusionPrescriptionVo> infusionPrescriptionVoList = bo.getInfusionPrescriptionVos();
            for (InfusionPrescriptionVo prescriptionVo : infusionPrescriptionVoList) {
                InfusionItem infusionItem = new InfusionItem();
                infusionItem.setItemId(prescriptionVo.getItemId());
                infusionItem.setRegisterId(add.getInfusionRegisterId());
                infusionItem.setGroupNumber(prescriptionVo.getGroupNumberShow());
                PerformFreqDictVo performFreqDictVo = StringUtils.isNotBlank(prescriptionVo.getPerformFreq()) && CollectionUtil.isNotEmpty(performFreqDictMap)
                        ? performFreqDictMap.get(prescriptionVo.getPerformFreq()) : null;
                if (performFreqDictVo != null) {
                    infusionItem.setInfusionNumber(performFreqDictVo.getFreqCounter().intValue() * prescriptionVo.getAbidance());
                }
                infusionItem.setInfusionDay(prescriptionVo.getAbidance());
                infusionItem.setOrgId(add.getOrgId());
                infusionItem.setOrgName(orgName);
                infusionItem.initEntity();
                infusionItemList.add(infusionItem);
            }
            infusionItemMapper.insertBatch(infusionItemList);
            // 全选
            if (StringUtils.equals(bo.getIsAll(), UserConstants.YES)) {
                // 删除 输液室待登记
                infusionRegisterStayMapper.delete(Wrappers.<InfusionRegisterStay>lambdaQuery()
                        .eq(InfusionRegisterStay::getClinicId, bo.getClinicId())
                );
            }
            // 处方明细id
            List<String> itemIdCollect = infusionPrescriptionVoList.stream().map(InfusionPrescriptionVo::getItemId).collect(Collectors.toList());
            prescriptionItemMapper.update(Wrappers.<PrescriptionItem>lambdaUpdate()
                    .in(PrescriptionItem::getItemId, itemIdCollect)
            );
        }
        return flag;
    }

    /**
     * 修改输液室登记主
     */
    @Override
    public Boolean updateByBo(InfusionRegisterBo bo) {
        InfusionRegister update = BeanUtil.toBean(bo, InfusionRegister.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(InfusionRegister entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除输液室登记主
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 获取输液室登记患者信息
     *
     * @param page
     * @param bo
     * @return
     */
    @Override
    public TableDataInfo<ClinicMasterVo> listInfusionRegisterInfoList(InfusionRegisterBo bo, PageQuery pageQuery) {
        Map<String, Object> params = bo.getParams();
        if (params.get("beginTime") != null && params.get("endTime") != null) {
            bo.setBeginTime(DateUtils.dateTime(params.get("beginTime")));
            bo.setEndTime(DateUtils.dateTime(params.get("endTime")));
        }
        Page<ClinicMasterVo> infusionRegisterList = baseMapper.listInfusionRegisterInfoList(pageQuery.build(), bo);
        List<String> clinicIds = new ArrayList<>();
        List<HisDiagnosisVo> hisDiagnosisVos = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(infusionRegisterList.getRecords())) {
            clinicIds = infusionRegisterList.getRecords().stream().map(ClinicMasterVo::getId).collect(Collectors.toList());
            // 获取诊断信息
            hisDiagnosisVos = hisDiagnosisMapper.selectVoList(Wrappers.<HisDiagnosis>lambdaQuery()
                    .in(HisDiagnosis::getClinicId, clinicIds)
            );
        }
        List<HisDiagnosisVo> finalHisDiagnosisVos = hisDiagnosisVos;
        infusionRegisterList.getRecords().forEach(item -> {
            StringBuilder diagnosisStr = new StringBuilder();
            List<HisDiagnosisVo> diagnosisVoCollect = finalHisDiagnosisVos.stream()
                    .filter(e -> StringUtils.equals(e.getClinicId(), item.getId())).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(diagnosisVoCollect)) {
                for (HisDiagnosisVo vo : diagnosisVoCollect) {
                    diagnosisStr.append(vo.getIcdName()).append(";");
                }
            }
        });
        return TableDataInfo.build(infusionRegisterList);
    }


    /**
     * 查询输液室登记主列表+ 药品详情 (不分页)
     *
     * @param bo
     * @return
     */
    @Override
    public List<InfusionPrescriptionVo> listInfusionRegisterAndPrescItem(InfusionRegisterBo bo) {
        return initGroupNumberStyle(baseMapper.listInfusionRegisterAndPrescItem(bo));
    }

    /**
     * 组织分组号 括号显示
     *
     * @param prescriptionVoList
     * @return
     */
    public List<InfusionPrescriptionVo> initGroupNumberStyle(List<InfusionPrescriptionVo> prescriptionVoList) {
        // ┍ ┕ ┌ ├ └     ╭│╰ ┆
        for (int i = 0; i < prescriptionVoList.size(); i++) {
            // 当前key值
            String currentKey = String.valueOf(prescriptionVoList.get(i).getGroupNumber());
            // 上一条
            String previousKey = "";
            // 下一条
            String lastKey = "";
            if (i >= 1) {
                previousKey = String.valueOf(prescriptionVoList.get(i - 1).getGroupNumber());
            }
            if (i < prescriptionVoList.size() - 1) {
                lastKey = String.valueOf(prescriptionVoList.get(i + 1).getGroupNumber());
            }
            if (!StringUtils.equals(currentKey, previousKey) && !StringUtils.equals(currentKey, lastKey)) {
                // 当前key != 上一条key && 当前key ！= 下一条key 表示没有组号 不设置标记
                prescriptionVoList.get(i).setGroupNumberStyle("");
                prescriptionVoList.get(i).setGroupNumberShow(prescriptionVoList.get(i).getGroupNumber());

            } else if (!StringUtils.equals(currentKey, previousKey) && StringUtils.equals(currentKey, lastKey)) {
                // 当前key ！= 前一条key && 当前key == 下一条key 设置组号 开始 标记
                prescriptionVoList.get(i).setGroupNumberStyle("┌");
                prescriptionVoList.get(i).setGroupNumberShow(prescriptionVoList.get(i).getGroupNumber());
            } else if (StringUtils.equals(currentKey, previousKey) && StringUtils.equals(currentKey, lastKey)) {
                // 当前key == 上一条key
                prescriptionVoList.get(i).setGroupNumberStyle("├");
                prescriptionVoList.get(i).setGroupNumberShow(prescriptionVoList.get(i).getGroupNumber());
            } else if (StringUtils.equals(currentKey, previousKey) && !StringUtils.equals(currentKey, lastKey)) {
                // 当前key == 上一条key && 当前key ！= 下一条key 表示分组的最后一条 设置 结束 标记
                prescriptionVoList.get(i).setGroupNumberStyle("└");
                prescriptionVoList.get(i).setGroupNumberShow(prescriptionVoList.get(i).getGroupNumber());
            }
        }
        return prescriptionVoList;
    }
}
